<template>
  <div class="LoginBack" style="background-image:url('static/img/login.png')">
    <el-container>
      <el-header height='300px'></el-header>
      <el-main>
        <el-row type='flex' justify='center' :gutter='20'>
          <el-col :span='7' class="logininput">
            <el-col :span="4">&nbsp;</el-col>
            <el-col :span="16">
              <el-form :model="user" :rules="rules" ref="user" status-icon hide-required-asterisk>
                <el-form-item label="用户名" prop="account">
                  <el-input v-model="user.account" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="user.password" type='password' placeholder="密码"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code" required>
                  <el-input v-model="user.code" placeholder="验证码"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm">登录</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="4"></el-col>
          </el-col>
        </el-row>
      </el-main>
      <el-footer height=''></el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    // 自定义校验写这里
    // 定义校验规则
    let checkcode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.length !== 4) {
        callback(new Error('请输入4位验证码'))
      } else {
        callback()
      }
    }
    return {
      user: {
        account: '',
        password: '',
        code: ''
      },
      rules: {
        account: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        code: [{ validator: checkcode, trigger: 'blur' }]
      }
    }
  },
  beforeCreate() {},
  methods: {
    async submitForm() {
      // 前台校验
      this.$refs['user'].validate(async r => {
        if (!r) return false
        let res = await this.post('login')
        if (res) {
          await this.$store.commit('login', [this.user.account, res.sessionId])
          this.$router.replace('/main')
        }
      })
    }
  }
}
</script>

<style scoped>
.LoginBack {
  width: 100%;
  height: 100%;
  position: absolute;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;
}
.logininput {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 2%;
}
</style>
